import datetime
import time
from concurrent.futures import ThreadPoolExecutor
import pandas as pd
from main_class import *
import Global_param as g


# 判断当前时间是否是规定时间

def is_now(set_now, time_level):
    """

    Parameters
    ----------
    set_now 设定的时间
    time_level 判断日期，小时，分钟，还是秒

    Returns
    -------
    例如：
    result = is_now('10:33:30', 'second')
    result = is_now('2021.12.10', 'day')
    """
    ts_set = pd.Timestamp(set_now)
    ts_now = pd.Timestamp(datetime.datetime.now())
    if time_level == 'day':
        if ts_set.year == ts_now.year and ts_set.month == ts_now.month and ts_set.day == ts_now.day:
            return True
        else:
            return False
    elif time_level == 'hour':
        if ts_set.hour == ts_now.hour:
            return True
        else:
            return False
    elif time_level == 'minute':
        if ts_set.hour == ts_now.hour and ts_set.minute == ts_now.minute:
            return True
        else:
            return False
    elif time_level == 'second':
        if ts_set.hour == ts_now.hour and ts_set.minute == ts_now.minute and ts_set.second == ts_now.second:
            return True
        else:
            return False
    elif time_level == 'year':
        if ts_set.year == ts_now.year:
            return True
        else:
            return False


# 登录账户并创建相关文件
def day_task1():
    os.system('python ./main_class.py')



class StockSystem(object):
    def __init__(self):
        timePrintLog('开始记录行情主程序')
        self.pool_day = ThreadPoolExecutor(5)

    def onstart(self):
        # 创建监控文件
        initProcessMonitor()
        ts = pd.Timestamp(datetime.datetime.now())
        timePrintLog('现在时间是：{}'.format(ts.now()))
        while True:
            ts = pd.Timestamp(datetime.datetime.now())
            if ts.minute % 5 == 0:
                # timePrintLog('开始执行5分钟程序程序')
                self.ontimer()
                time.sleep(300)
            else:
                time.sleep(60 * ((5 - ts.minute % 5) % 5))

    def ontimer(self):
        process_monitor()

        if is_now('8:45', 'minute'):
            self.pool_day.submit(day_task1, )
        elif is_now('20:45', 'minute'):
            self.pool_day.submit(day_task1, )



def main():
    stock_wang = StockSystem()
    stock_wang.onstart()


if __name__ == '__main__':
    main()
